package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"path"
	"shops/models"
	"strings"
	"time"
)

type ShopController struct {
	beego.Controller
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	status := c.GetString("status")
	address := c.GetString("address")
	shop := models.Shop{
		Name:     name,
		Img:      img,
		Status:   status,
		SaleTime: time.Now(),
		Address:  address,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = JsonRes{
		Code: 200,
		Msg:  "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件获取失败",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件过大",
		}
		c.ServeJSON()
		return
	}
	allowFile := map[string]bool{
		".png":  true,
		".jpeg": true,
	}
	ext := strings.ToLower(path.Ext(header.Filename))
	if !allowFile[ext] {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件类型错误，只允许png,jpeg,jpg格式",
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "上传失败",
		}
		c.ServeJSON()
		return
	} else {
		imgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
		return
	}

}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 10)
	var count int64
	err := models.DB.Model(&models.Shop{}).Count(&count).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "总数查询失败",
		}
		c.ServeJSON()
		return
	}
	var shop []models.Shop
	offset := (page - 1) * size
	err = models.DB.Model(&models.Shop{}).Limit(size).Offset(offset).Find(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "列表查询失败",
		}
		c.ServeJSON()
		return
	}
	pageData := make(map[string]interface{})
	pageData["count"] = count
	pageData["shop"] = shop

	c.Data["json"] = JsonRes{
		Code: 200,
		Msg:  "查询成功",
		Data: pageData,
	}
	c.ServeJSON()
	return

}
